﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace VH.SharePoint.Api.Helpers
{
    internal static class SPWebConfigHelper
    {
        public static void AddWebConfigModification(SPWebApplication webApplication, SPWebConfigModification modification)
        {
            var existing = webApplication.WebConfigModifications.FirstOrDefault(c => c.Name.Equals(modification.Name));
            if (existing != null)
            {
                webApplication.WebConfigModifications.Remove(existing);
            }
            webApplication.WebConfigModifications.Add(modification);
            webApplication.Update();
            SPFarm.Local.Services.GetValue<SPWebService>(webApplication.Parent.Id).ApplyWebConfigModifications();
        }
        public static void RemoveWebConfigModificationsByOwner(SPWebApplication webApplication, String owner)
        {
            var modificationCollection = webApplication.WebConfigModifications;
            var removeCollection = new Collection<SPWebConfigModification>();

            var count = modificationCollection.Count;
            for (var i = 0; i < count; i++)
            {
                var modification = modificationCollection[i];
                if (modification.Owner == owner)
                {
                    // collect modifications to delete
                    removeCollection.Add(modification);
                }
            }

            // now delete the modifications from the web application
            if (removeCollection.Count > 0)
            {
                foreach (SPWebConfigModification modificationItem in removeCollection)
                {
                    webApplication.WebConfigModifications.Remove(modificationItem);
                }

                // Commit modification removals to the specified web application
                webApplication.Update();

                // Push modifications through the farm
                SPFarm.Local.Services.GetValue<SPWebService>(webApplication.Parent.Id).ApplyWebConfigModifications();
            }
        }
    }
}
